package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = {"${myRabbitmq.MQConfig.queues}"})
public class ReleaseStockListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 需要解锁的情况：
     * 1，订单下单成功，锁库存成功，其他业务失败，没有分布式事务，则需要解锁库存
     * 2，订单失败由于远程锁库存不成功，则需要判断有没有库存工作单，没有则不需要解锁库存，因为库存单，详情等已经回滚
     *
     */
    @RabbitHandler
    public void releaseLockedStock(StockLockedTo to, Message message, Channel channel) throws IOException {
        try{
            wareSkuService.releaseLockedStock(to);
            //消息手动确认之后mq会删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //拒绝之后重新入队，消息不会删除
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
